package com.zys.sac.core.provider;

import com.zys.sac.core.helper.RSAOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 验证处理器，由于SpringSecurity在接收密码时默认使用的明文，会导致安全问题，
 * 该类提供了RSA方式的密码解密方式，前端在传递密码时使用RSA方式进行加密，在该
 * 类中进行密码解密，然后使用SpringSecurity进行验证（数据库中保存的是密文）
 *
 * Created by zhongjunkai on 2022/4/13.
 */
@Slf4j
public class RSAModeUserAuthenticationProvider extends AbstractSacUserAuthenticationProvider {

    @Autowired
    private RSAOperator rsaOperator;

    private PasswordEncoder bCryptPasswordEncoder;

    public RSAModeUserAuthenticationProvider(PasswordEncoder bCryptPasswordEncoder) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void doMatchPassword(String password, String dbPassword) {
        String rawPassword;
        try {
            //获取解密后的明文密码
            rawPassword = rsaOperator.decode(password);
        } catch (Exception e) {
            log.error("密码解密发生异常", e);
            throw new CredentialsExpiredException("用户名或密码错误");
        }
        if(!bCryptPasswordEncoder.matches(rawPassword, dbPassword)) {
            throw new CredentialsExpiredException("用户名或密码错误");
        }
    }
}
